package com.xxwy.ddu.security.app.social.signup;

import com.xxwy.ddu.security.code.util.SignUpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @author xxwy
 * on 2018/8/29 0029
 * app环境下替换providerSignInUtils，避免由于没有session导致读不到社交用户信息的问题
 */
@Component
public class AppSignUpUtils implements SignUpUtils {

    @Autowired
    RedisTemplate<String,Serializable> xxredisTemplate;

    @Autowired
    private UsersConnectionRepository usersConnectionRepository;

    @Autowired
    private ConnectionFactoryLocator connectionFactoryLocator;

    @Override
    public void saveConnectionData(WebRequest request, ConnectionData connectionData){
        xxredisTemplate.opsForValue().set(getkey(request),connectionData,10,TimeUnit.MINUTES);
    }

    private String getkey(WebRequest request) {
        String deviceId = request.getHeader("deviceId");
        if(StringUtils.isBlank(deviceId)){
            throw new RuntimeException("设备deviceId不能为null");
        }
        return "xxwy:security:social.connect" + deviceId;
    }

    /**
     * 绑定
     * @param request
     * @param userId
     */
    @Override
    public void doPostSignUp(WebRequest request,String userId){
        //从redis中获取Connection数据，绑定在userConnection表中
        String key = getkey(request);
        if(!xxredisTemplate.hasKey(key)){
            throw new RuntimeException("无法从缓存中拿到用户社交信息");
        }
        ConnectionData connectionData = (ConnectionData)xxredisTemplate.opsForValue().get(key);
        Connection<?> connection = connectionFactoryLocator.getConnectionFactory(connectionData.getProviderId()).createConnection(connectionData);
        usersConnectionRepository.createConnectionRepository(userId)
                .addConnection(connection);
    }
}
